package com.kedll.library.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;

import com.kedll.library.R;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 金额输入框
 * Created by QiQi on 16/3/10.
 */
public class MoneyEditText extends EditText {
    public void setTextWatcher(TextWatcher textWatcher) {
        this.textWatcher = textWatcher;
    }

    TextWatcher textWatcher;
    int pointNum;

    public MoneyEditText(Context context) {
        this(context, null);
    }

    public MoneyEditText(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MoneyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MoneyEditText, defStyleAttr, 0);
        pointNum = a.getInteger(R.styleable.MoneyEditText_pointNum, 2);
        a.recycle();
        final InputFilter[] filters = {new EditInputFilter(pointNum)};

        setFilters(filters);
        setFocusableInTouchMode(true);
        setFocusable(true);

        if(getHint() == null) {
            setHint(String.format("%." + pointNum + "f", 0f));
        }

//        addTextChangedListener(new TextWatcher() {
//            private boolean isChanged = false;
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before,
//                                      int count) {
//                // TODO Auto-generated method stub
//                if (textWatcher != null) {
//                    textWatcher.onTextChanged(s, start, before, count);
//                }
//            }
//
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count,
//                                          int after) {
//                // TODO Auto-generated method stub
//                if (textWatcher != null) {
//                    textWatcher.beforeTextChanged(s, start, count, after);
//                }
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                // TODO Auto-generated method stub
//                if (isChanged) {// ----->如果字符未改变则返回
//                    return;
//                }
//                String str = s.toString();
////
//                isChanged = true;
//                String cuttedStr = str;
////                /* 删除字符串中的dot */
////                for (int i = str.length() - 1; i >= 0; i--) {
////                    char c = str.charAt(i);
////                    if ('.' == c) {
////                        cuttedStr = str.substring(0, i) + str.substring(i + 1);
////                        break;
////                    }
////                }
////                /* 删除前面多余的0 */
////                int NUM = cuttedStr.length();
////                int zeroIndex = -1;
////                for (int i = 0; i < NUM - pointNum; i++) {
////                    char c = cuttedStr.charAt(i);
////                    if (c != '0') {
////                        zeroIndex = i;
////                        break;
////                    } else if (i == NUM - (pointNum + 1)) {
////                        zeroIndex = i;
////                        break;
////                    }
////                }
////                if (zeroIndex != -1) {
////                    cuttedStr = cuttedStr.substring(zeroIndex);
////                }
////                /* 不足3位补0 */
////                if (cuttedStr.length() < (pointNum + 1)) {
////                    cuttedStr = "0" + cuttedStr;
////                }
////                /* 加上dot，以显示小数点后两位 */
////                cuttedStr = cuttedStr.substring(0, cuttedStr.length() - pointNum)
////                        + "." + cuttedStr.substring(cuttedStr.length() - pointNum);
//
//                if (cuttedStr.length() > 1 && !cuttedStr.contains(".")) {
//                    if (cuttedStr.startsWith("0")) {
//                        cuttedStr = cuttedStr.substring(1);
//                    }
//                } else if (cuttedStr.contains(".")) {//包含小数的
//                    String[] splits = cuttedStr.split("\\.");
//                    String first = splits[0];
//                    if (first.length() > 1 && first.startsWith("0")) {//当整数部分大于1位数时,不能以0开头
//                        first = first.substring(1);
//                    }
//                    String end = "";
//                    if(splits.length > 1) {
//                        end = splits[1];
//                        if (end.length() > pointNum) {//当小数部分的长度大于要保留的位数,截取有效部分
//                            end = end.substring(0, pointNum);
//                        }
//                    }
//
//                    cuttedStr = first.concat(".").concat(end);
//                }
////
//                setText(cuttedStr);
////
//                setSelection(length());
//                isChanged = false;
//                if (textWatcher != null) {
//                    textWatcher.afterTextChanged(s);
//                }
//            }
//        });
    }

    public void setMoney(double money) {
        setText(new BigDecimal(money).setScale(pointNum, BigDecimal.ROUND_HALF_DOWN).toPlainString());
    }



    /**
     * joy on 2015/12/17.
     * 金额输入格式
     */

    public class EditInputFilter implements InputFilter {

        /**
         * 最大数字，我们取int型最大值
         */

        public static final int MAX_VALUE = 2147483647;

        /**
         * 小数点后的数字的位数
         */

        public int PONTINT_LENGTH = 2;

        Pattern p;

        public EditInputFilter(int pointNum) {
            PONTINT_LENGTH = pointNum;
            p = Pattern.compile("[0-9]*");   //除数字外的其他的

        }

        /**
         * source    新输入的字符串
         * start    新输入的字符串起始下标，一般为0
         * end    新输入的字符串终点下标，一般为source长度-1
         * dest    输入之前文本框内容
         * dstart    原内容起始坐标，一般为0
         * dend    原内容终点坐标，一般为dest长度-1
         */

        @Override

        public CharSequence filter(CharSequence src, int start, int end,

                                   Spanned dest, int dstart, int dend) {

            String oldText = dest.toString();

            System.out.println(oldText);

            //验证删除等按键

            if ("".equals(src.toString())) {

                return null;

            }

            //验证非数字或者小数点的情况

            Matcher m = p.matcher(src);

            if (oldText.contains(".")) {

                //已经存在小数点的情况下，只能输入数字

                if (!m.matches()) {

                    return null;

                }

            } else {

                //未输入小数点的情况下，可以输入小数点和数字

                if (!m.matches() && !src.equals(".")) {

                    return null;
                }

            }

            //验证输入金额的大小

            if (!src.toString().equals("")) {

                double dold = Double.parseDouble(oldText + src.toString());

                if (dold > MAX_VALUE) {

                    return dest.subSequence(dstart, dend);

                } else if (dold == MAX_VALUE) {

                    if (src.toString().equals(".")) {

                        return dest.subSequence(dstart, dend);
                    }

                }

            }

            //验证小数位精度是否正确

            if (oldText.contains(".")) {

                int index = oldText.indexOf(".");

                int len = dend - index;

                //小数位只能2位

                if (len > PONTINT_LENGTH) {

                    CharSequence newText = dest.subSequence(dstart, dend);

                    return newText;
                }
            }

            return dest.subSequence(dstart, dend) + src.toString();

        }

    }

}
